<template>
    <div>
<!--        面包屑-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/goods">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
<!--        卡片区-->
        <el-card>
<!--            提示信息-->
            <el-row>
                <el-alert title="添加商品信息" type="info" :closable="false" center show-icon></el-alert>
            </el-row>
<!--            步骤条-->
            <el-row>
                <el-steps style="width: 100%;padding:5px;font-size:13px"
                          :span="200"
                          :active="activeIndex"
                          align-center
                          finish-status="success">
                    <el-step title="基本信息"></el-step>
                    <el-step title="商品参数"></el-step>
                    <el-step title="商品属性"></el-step>
                    <el-step title="商品图片"></el-step>
                    <el-step title="商品内容"></el-step>
                    <el-step title="完成"></el-step>
                </el-steps>
            </el-row>
<!--            tab面板-->
<!--            label-position控制label位置-->
            <el-form :model="addGoodForm"
                     :rules="addGoodFormRules"
                     label-width="100px"
                     label-position="top"
                     ref="addGoodFormRef">
                <el-tabs tab-position="left"
                         :before-leave="beforTabLeave"
                         @tab-click="tabClicked"
                         v-model="activeIndex">
                    <el-tab-pane name="0" label="基本信息">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addGoodForm.goods_name" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addGoodForm.goods_price" placeholder="请输入商品价格" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addGoodForm.goods_weight" placeholder="请输入商品重量" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addGoodForm.goods_number" placeholder="请输入商品数量" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                    style="width: 100%"
                                    v-model="addGoodForm.goods_cat"
                                    :options="cateList"
                                    :props="cascaderProps"
                                    @change="handleChange"></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="1" label="商品参数">
                        <el-form-item v-for="(item,index) in manyAttributeList" :key="index"
                                      :label="item.attr_name">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox 
                                  v-for="item1 in item.attr_vals"
                                  :key='item1'
                                  border
                                  :label="item1">
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="2" label="商品属性">
                        <el-form-item v-for="(item,index) in onlyAttributeList"
                                      :key="index"
                                      :label="item.attr_name">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane name="3" label="商品图片">
                        <el-upload
                                action="http://127.0.0.1:8888/api/private/v1/upload"
                                :headers = 'headersObj'
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                :on-success="handleSuccess"
                                list-type="picture">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane name="4" label="商品内容">
<!--                        富文本编辑器-->
                        <QuillEditor
                                style="height:200px"
                                v-model="addGoodForm.goods_induction"
                                     @update:content="textchange"
                                     :options="quillEditorProps"/>
                        <el-button style="margin-top: 10px"
                                   @click="sureAddGood"
                                   type="primary">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
<!--        图片预览dialog-->
        <el-dialog title="图片预览" v-model="imgPreviewDialogVisible" width="50%">
            <img style="width: 100%" :src="previewPath"/>
        </el-dialog>
    </div>
</template>

<script>
  export default {
    name: "addGood",
    components:{

    },
    data(){
      return {
        activeIndex:'0',//激活的item
        addGoodForm:{//添加商品表单
          goods_name:'',
          goods_price:'',
          goods_weight:'',
          goods_number:'',
          goods_cat:[],//提交时需要转为字符串
          goods_induction:'',//商品详情
          pics:[],
          attrs:[],
        },
        addGoodFormRules:{
          goods_name:[{required:true,message:'请输入商品名称',trigger:'blur'}],
          goods_price:[{required:true,message:'请输入商品价格',trigger:'blur'}],
          goods_weight:[{required:true,message:'请输入商品重量',trigger:'blur'}],
          goods_number:[{required:true,message:'请输入商品数量',trigger:'blur'}],
          goods_induction:[{required:true,message:'请输入商品介绍',trigger:'blur'}],
          goods_cat:[{required:true,message:'请选择商品分类',trigger:'blur'}],
        },
        cateList:[],//分类列表
        cascaderProps:{//级联选择器配置项
          value:'cat_id',
          label:'cat_name',
          children:'children',
        },
        manyAttributeList:[],//动态参数列表
        onlyAttributeList:[],//静态属性列表
        headersObj:{
          Authorization:window.sessionStorage.getItem('Token')
        },
        previewPath:'',//预览图片路径
        imgPreviewDialogVisible:false,//图片预览dialog
        quillEditorProps:{//富文本编辑器配置项
          debug: 'info',
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
              ['blockquote', 'code-block'],

              [{ 'header': 1 }, { 'header': 2 }],               // custom button values
              [{ 'list': 'ordered'}, { 'list': 'bullet' }],
              [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
              [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
              [{ 'direction': 'rtl' }],                         // text direction

              [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

              [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
              [{ 'font': [] }],
              [{ 'align': [] }],

              ['clean']                                         // remove formatting button
            ]
          },
          placeholder: '请简单描述商品',
          readOnly: false,
          theme: 'snow'
        }
      }
    },
    created() {
      this.getCateList();
    },
    methods:{
      //获取商品分类数据
      async getCateList(){
        const {data:res} = await this.$http.get(`/categories`);
        this.cateList = res.data;
        console.log(this.cateList)
      },
      //级联选择器变化
      handleChange(){
        console.log(this.addGoodForm.goods_cat)
      },
      //监听tab项变化
      beforTabLeave(activeName,oldActiveName){
        if(oldActiveName === '0' && this.addGoodForm.goods_cat.length !== 3){
          this.$message.warning('请先选择商品分类')
          return false;
        }
      },
      //激活某个tab时触发
      tabClicked(){
        if(this.activeIndex === '1'){
            this.getManyAttributeList()
        }else if(this.activeIndex === '2'){
          this.getOnlyAttributeList()
        }
      },
      //获取动态参数选择
      async getManyAttributeList(){
        const {data:res} = await this.$http.get(`/categories/${this.cateId}/attributes`,{
          params:{
            sel:'many'
          }
        })
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        //将attr_vals转为数组
        res.data.forEach(item =>{
          item.attr_vals = (item.attr_vals? item.attr_vals.split(' '):[]);
        })
        this.manyAttributeList = res.data;
        console.log(this.manyAttributeList)
      },
      //获取静态属性
      async getOnlyAttributeList(){
        const {data:res} = await this.$http.get(`/categories/${this.cateId}/attributes`,{
          params:{
            sel:'only'
          }
        })
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        //将attr_vals转为数组
        // res.data.forEach(item =>{
        //   item.attr_vals = (item.attr_vals? item.attr_vals.split(' '):[]);
        // })
        this.onlyAttributeList = res.data;
        console.log(this.onlyAttributeList)
      },
      //图片预览
      handlePreview(file){
        console.log(file);
        this.previewPath = file.response.data.url;
        this.imgPreviewDialogVisible = true;
      },
      //移除图片
      handleRemove(file,fileList){
        const filepath = file.response.data.tmp_path;
        const removeIndex = this.addGoodForm.pics.findIndex(item =>{
          item.pic === filepath
        })
        this.addGoodForm.pics.splice(removeIndex,1);
        console.log(this.addGoodForm.pics)
      },
      //图片上传成功
      handleSuccess(response,file,fileList){
        //console.log(response,file,fileList)
        const picInfo = {
          pic:response.data.tmp_path,
        }
        this.addGoodForm.pics.push(picInfo)
        console.log(this.addGoodForm.pics)
      },
      //富文本编辑器内容变化
      textchange(val){
        console.log(val)
        this.addGoodForm.goods_induction = val.ops[0].insert;
        console.log(this.addGoodForm.goods_induction)
      },
      //添加商品
      sureAddGood(){
        console.log(this.addGoodForm);
        this.$refs.addGoodFormRef.validate(async valid => {
          if(!valid){
            return this.$message.warning('请填写必要的表单内容')
          }
          //将goods_cat转为字符串
          //也可以使用lodash进行深拷贝
          this.addGoodForm.goods_cat = this.addGoodForm.goods_cat.join(',')
          //处理动态参数
          this.manyAttributeList.forEach(item =>{
            const newInfo = {attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')};
            this.addGoodForm.attrs.push(newInfo);
          })
          //处理静态属性
          this.onlyAttributeList.forEach(item =>{
            const newInfo = {attr_id:item.attr_id,attr_value:item.attr_vals};
            this.addGoodForm.attrs.push(newInfo);
          })
          //添加商品
          const {data:res} = await this.$http.post('/goods',this.addGoodForm);
          if(res.meta.status !== 201){
            return this.$message.error(res.meta.msg);
          }
          this.activeIndex = '6'
          this.$message.success(res.meta.msg);
          this.$router.push('/goods');
        })
      }

    },
    computed:{
      cateId(){
        if(this.addGoodForm.goods_cat.length === 3){
          return this.addGoodForm.goods_cat[2];
        }
      }
    }
  }
</script>

<style scoped>
.el-checkbox{
    margin:0 10px 0 0!important;
}
</style>
